package org.team4.dao.meta;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.hibernate.SessionFactory;
import org.team4.dao.GenericDAO;
import org.team4.domain.RoleModuleDepartments;
import org.team4.domain.RoleUsers;
import org.team4.util.CacheUtil;
import org.team4.util.Validate;
import org.team4.vo.RoleCache;

import org.team4.dao.meta.RoleModuleDepartmentsDAO;

/**
 * <p>程序名称：       RoleModuleDepartmentsDAO.java</p>
 * <p>程序说明：       角色模块的部门权限</p>
 * <p>版权信息：       Copyright 深圳市维远泰克科技有限公司</p>
 * <p>时间：          Jan 11, 2011 8:44:03 AM</p>	
 * 
 * @author：          Marker.King
 * @version：         Ver 0.1
 */
public class RoleModuleDepartmentsDAO extends GenericDAO<RoleModuleDepartments> {

	private static final long serialVersionUID = -4555796369325957225L;
	private static RoleModuleDepartmentsDAO instance;
	
	public static RoleModuleDepartmentsDAO getInstance(SessionFactory sessionFactory) {
        if(instance == null) {
            instance =  new RoleModuleDepartmentsDAO(sessionFactory);
        }
        return instance;
    }
	
	private RoleModuleDepartmentsDAO(SessionFactory sessionFactory) {
		super(sessionFactory, RoleModuleDepartments.class);
	}
	
	/**
	 * session用到的部门权限
	 * @param ruList
	 * @return
	 */
	public HashMap<String, String> findRoleModuleDepartments(List<RoleUsers> ruList, String userId) {
		//从缓存中取出现有权限
		HashMap<String, String> moduleDepartments = new HashMap<String, String>();
		RoleCache roleCache = (RoleCache) CacheUtil.get(RoleCache.CACHE_NAME, userId);
		if(roleCache != null) {
			moduleDepartments = roleCache.getModuleDepartments();
		}
		if (Validate.collectionNotNull(ruList)) {
            for (RoleUsers ru : ruList) {
                for (Iterator iter = ru.getRole().getRoleModuleDepartments().iterator(); iter.hasNext();) {
                	RoleModuleDepartments rmd = (RoleModuleDepartments) iter.next();
                    String sessionDepartments = moduleDepartments.get(rmd.getModule().getId());
                    StringBuffer departmentIds = new StringBuffer();
                    if (Validate.notNull(sessionDepartments))
                    	departmentIds.append(sessionDepartments);
                    String[] nextDepartmentsIds = rmd.getDepartments().split(",");
                    for (int i = 0; i < nextDepartmentsIds.length; i++) {
                        if (Validate.notNull(nextDepartmentsIds[i])) {
                            if (departmentIds.indexOf(nextDepartmentsIds[i]) < 0)
                            	departmentIds.append(nextDepartmentsIds[i] + ",");
                        }
                    }
                    moduleDepartments.put(rmd.getModule().getId(), departmentIds.toString());
                }
            }
        }
		return moduleDepartments;
	}

}
